import React, { useState, useEffect, useRef } from 'react';
import FormItem from '../../../components/FormItem';
import { Form, Input, InputNumber, Button, Row, Col, Select, message } from 'antd';
import useAppProductEventData from 'src/hook/useAppProductEventData';
import ReceiveUser from '../components/ReceiveUser';
import WarnConditions from '../components/WarnConditions';
import services from '../../../services/api';
// import DeptSelect from '../../../components/DeptSelect';

const layout = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};

function RiskAdd(props) {
  const { record = {}, form, closeModal, actionType } = props;
  const [strategyOptions, setStrategyOptions] = useState([]);
  const [versionOptions, setVersionOptions] = useState([]);
  const [ruleOptions, setRuleOptions] = useState([]);

  const WarnConditionsRef = useRef(null);

  const {
    id,
    monitor_name,
    app_id,
    product_id,
    event_id,
    monitor_period,
    monitor_period_unit,
    // received_emails,
    // status,
    // dept_ids = [],
    // dept_names = [],
    remark,
    users,
    condition_group,
    strategy_id,
    version,
    rule_id,
  } = record;

  const onEventChange = () => {
    form.setFieldsValue({
      strategy_id: undefined,
      version: undefined,
      rule_id: undefined,
    });
  };

  const { items, eventId } = useAppProductEventData({
    ...props,
    app_id,
    event_id,
    product_id,
    layout,
    disabled: actionType !== 'add',
    form,
    onEventChange,
  });

  // 根据事件获取策略
  useEffect(() => {
    getStrategyOptions(eventId);
  }, [eventId]);
  const getStrategyOptions = async (event_id) => {
    if (event_id) {
      const { code, data, msg } = await services.riskMonitor.allStrategy({
        event_id,
      });
      if (!code) {
        setStrategyOptions(data);
        if (strategy_id) {
          const cur = data.find(item => item.strategy_id === strategy_id)
          if (!cur) {
            form.setFieldsValue({ strategy_id: undefined })
            message.warn('关联策略已删除，请重新选择')
          }
        }
      } else {
        message.warning(msg);
      }
    } else {
      setStrategyOptions([]);
    }
  };

  // 根据策略和事件 获取版本
  useEffect(() => {
    getVersionOptions(form.getFieldValue('strategy_id'), eventId);
  }, [form.getFieldValue('strategy_id'), eventId]);
  const getVersionOptions = async (strategy_id, event_id) => {
    if (strategy_id && event_id) {
      const { code, data, msg } = await services.riskMonitor.allVersion({
        strategy_id,
        event_id,
      });
      if (!code) {
        setVersionOptions(data);
      } else {
        message.warning(msg);
      }
    } else {
      setVersionOptions([]);
    }
  };

  // 根据策略和版本 获取规则
  useEffect(() => {
    getRuleOptions(form.getFieldValue('strategy_id'), form.getFieldValue('version'));
  }, [form.getFieldValue('strategy_id'), form.getFieldValue('version')]);
  const getRuleOptions = async (strategy_id, version) => {
    if (strategy_id && version) {
      const { code, data, msg } = await services.riskMonitor.allRule({
        strategy_id,
        version,
      });
      if (!code) {
        setRuleOptions(data);
      } else {
        message.warning(msg);
      }
    } else {
      setRuleOptions([]);
    }
  };

  // 策略改变
  const handleStrategyChange = () => {
    form.setFieldsValue({
      version: undefined,
      rule_id: undefined,
    });
  };

  // 版本改变
  const handleVersionChange = () => {
    form.setFieldsValue({
      rule_id: undefined,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        const { status, users: tempUsers } = values;
        const params = {
          ...values,
          status: status || 1,
          // received_emails: recerived_emails.length > 0 && recerived_emails.split(','),
        };
        try {
          // 接收人
          if (tempUsers.some((item) => !item.phone && !item.wx_work && !item.email)) {
            throw '请至少填写一种接收方式';
          }
          params.users = tempUsers.filter(Boolean).map((item) => {
            const { key, label } = item.user_id;
            item['name'] = Array.isArray(label) ? label[0] : label;
            item['user_id'] = key;
            return item;
          });
          // 条件
          WarnConditionsRef.current.getValue((error, values) => {
            if (!error) {
              params['condition_group'] = values;
            } else {
              throw error;
            }
          });
        } catch (error) {
          return message.warning(error);
        }
        // 可见部门
        // params.dept_ids = dept_ids.map((item) => item.value);
        // const recerived_emails =
        //   values.received_emails && values.received_emails.replace(/\n/g, ',').replace(/\s/g, '');
        // if (recerived_emails.length === 0) {
        //   message.warning('请输入正确的发送邮件');
        //   return;
        // }
        services.riskMonitor[actionType]({ ...params, id }).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            closeModal && closeModal();
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  const formItems = [
    {
      label: {
        label: '监控名称',
        ...layout,
      },
      name: 'name',
      options: {
        initialValue: monitor_name,
        rules: [
          { required: true, message: '请输入监控名称' },
          { max: 128, message: '最长128个字符' },
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9_]{1,}$/,
            message: '仅支持英文数字下划线中文',
          },
        ],
      },
      component: <Input placeholder='请输入监控名称' />,
    },
    ...items,
    {
      label: {
        label: '关联策略',
        ...layout,
      },
      name: 'strategy_id',
      options: {
        initialValue: strategy_id,
      },
      component: (
        <Select placeholder='请选择' allowClear onChange={handleStrategyChange}>
          {strategyOptions.map((item) => {
            return (
              <Select.Option value={item.strategy_id} key={item.strategy_id}>
                {item.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '关联版本',
        ...layout,
      },
      name: 'version',
      options: {
        initialValue: version,
      },
      component: (
        <Select allowClear placeholder='请选择' onChange={handleVersionChange}>
          {versionOptions.map((item) => {
            return (
              <Select.Option value={item.version} key={item.version}>
                {item.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '关联规则',
        ...layout,
      },
      name: 'rule_id',
      options: {
        initialValue: rule_id,
      },
      component: (
        <Select allowClear placeholder='请选择'>
          {ruleOptions.map((item) => {
            return (
              <Select.Option value={item.rule_id} key={item.rule_id}>
                {item.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
  ];
  const formItems_level1 = [
    {
      name: 'monitor_period',
      options: {
        initialValue: monitor_period,
        rules: [{ required: true, message: '请选择' }],
      },
      component: <InputNumber min={1} step={1} placeholder='请输入' style={{ width: '100%' }} />,
    },
    {
      name: 'monitor_period_unit',
      options: {
        initialValue: monitor_period_unit,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select>
          {props.monitor_period_unit.map((it) => {
            return (
              <Select.Option value={it.code} key={it.code}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
  ];
  // const formItems_level2 = [
  //   {
  //     name: 'oper',
  //     options: {
  //       initialValue: oper,
  //       rules: [{ required: true, message: '请选择' }],
  //     },
  //     component: (
  //       <Select>
  //         {props.monitor_oper.map((it) => {
  //           return (
  //             <Select.Option value={it.code} key={it.code}>
  //               {it.value}
  //             </Select.Option>
  //           );
  //         })}
  //       </Select>
  //     ),
  //   },
  //   {
  //     name: 'threshold_value',
  //     options: {
  //       initialValue: threshold_value,
  //       rules: [{ required: true, message: '请选择' }],
  //     },
  //     component: <InputNumber min={0} step={1} style={{ width: '100%' }} placeholder='请输入' />,
  //   },
  // ];
  const formItems3 = [
    // {
    //   label: {
    //     label: '发送邮件',
    //    ...layout
    //   },
    //   name: 'received_emails',
    //   options: {
    //     initialValue: received_emails instanceof Array ? received_emails.join('\n') : '',
    //     rules: [{ required: true, message: '请输入' }],
    //   },
    //   component: (
    //     <Input.TextArea
    //       placeholder='每行请输入一个邮箱地址,输入完成后回车换行，&#10;实例:&#10;ABC@qq.com&#10;BCD@gmail.com'
    //       style={{ height: '90px' }}
    //     />
    //   ),
    // },
    // {
    //   label: {
    //     label: '状态',
    //    ...layout
    //   },
    //   name: 'status',
    //   options: {
    //     valuePropName: 'checked',
    //     initialValue: status === 2 ? false : true,
    //     rules: [{ required: true, message: '请选择' }],
    //   },
    //   component: <Switch />,
    // },
    // DeptSelect({
    //   treeCheckable: true, // 是否多选
    //   treeCheckStrictly: true, // 多选时是否取消父子关联
    //   deptTree: depts, // 全部部门数据
    //   deptArr: {
    //     ids: dept_ids,
    //     name: dept_names,
    //   }, // 当前部门数据
    //   hasRight: true, // 是否需要权限展示
    //   nodeDisabled: (item) => !item.dept_id, // 节点禁选
    //   layout: {
    //     label: '可见部门',
    //     ...layout,
    //   },
    //   rules: [{ required: true, message: '请选择' }],
    // }),
    {
      label: {
        label: '监控说明',
        ...layout,
      },
      name: 'remark',
      options: {
        initialValue: remark,
      },
      component: <Input.TextArea placeholder='请输入监控说明' />,
    },
  ];
  return (
    <div className='tantuer-form'>
      <Form onSubmit={() => false} className='login-form'>
        <div className='tantuer-field-area'>
          <Row type='flex'>
            {formItems.map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem {...props} form={form} item={item} colNum={2} />
                </Col>
              );
            })}
          </Row>
          <Row type='flex'>
            <Col className='ant-form-item-label' span={3}>
              <label className='ant-form-item-required'>监控周期</label>
            </Col>
            <Col span={21} className='flex-1'>
              <Row type='flex' gutter={10}>
                {formItems_level1.map((item) => {
                  return (
                    <Col span={12} key={item.name}>
                      <FormItem {...props} form={form} item={item} colNum={2} />
                    </Col>
                  );
                })}
              </Row>
            </Col>
          </Row>

          {/* <Row type='flex' className='tantuer-form-item2 tantuer-form-item-nowrap'>
            <Col className='ant-form-item-label'>
              <label className='ant-form-item-required'>条件</label>
            </Col>
            <Col span={18} className='flex-1'>
              <Row type='flex' gutter={10}>
                {formItems_level2.map((item) => {
                  return (
                    <Col span={12} key={item.name}>
                      <FormItem form={form} item={item} colNum={2} />
                    </Col>
                  );
                })}
              </Row>
            </Col>
          </Row> */}
          <Row type='flex'>
            <Col className='ant-form-item-label' span={3}>
              <label className='ant-form-item-required'>接收人</label>
            </Col>
            <Col className='ant-form-item-control-wrapper' span={21}>
              <ReceiveUser {...props} value={users} />
            </Col>
          </Row>
          <Row type='flex'>
            <Col className='ant-form-item-label' span={3}>
              <label className='ant-form-item-required'>预警条件</label>
            </Col>
            <Col className='ant-form-item-control-wrapper' span={21}>
              <WarnConditions {...props} value={condition_group} createRef={WarnConditionsRef} />
            </Col>
          </Row>
          <Row type='flex'>
            {formItems3.map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem {...props} form={form} item={item} colNum={2} />
                </Col>
              );
            })}
          </Row>
        </div>
        {actionType !== 'detail' && (
          <div className='form-btn'>
            <Button type='primary' onClick={handleSubmit} className='login-form-button' autoFocus={true}>
              确定
            </Button>
            <Button className='login-form-button' onClick={() => props.closeModal(true)}>
              取消
            </Button>
          </div>
        )}
      </Form>
    </div>
  );
}

export default Form.create()(RiskAdd);
